package com.example.utils;
 
import java.io.IOException;
import java.io.StringWriter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * bean转json格式或者json转bean格式, 项目中我们通常使用这个工具类进行json---java互相转化
 */
public class JacksonUtil {
	private static ObjectMapper mapper = new ObjectMapper();

	static {
		mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
				.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
				.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}
 
	public static String bean2Json(Object obj){
		StringWriter sw = new StringWriter();
		try{
			JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
			mapper.writeValue(gen, obj);
			gen.close();
			return sw.toString();
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
 
	public static <T> T json2Bean(String jsonStr, Class<T> objClass){
		try {
			return mapper.readValue(jsonStr, objClass);
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}

	}

	public static <T> T json2Bean(String jsonStr, TypeReference<T> typeReference) {
		try {
			return mapper.readValue(jsonStr, typeReference);
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}

	}}